/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

/**
 *
 * @author Nut
 */
public class FeedWriter extends HttpServlet {

    static String strLink;

    public FeedWriter() {
        super();
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/xml; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter pw = response.getWriter();

        String strTitle = request.getParameter("title");
        strLink = request.getParameter("link");
        String strDisc = request.getParameter("dis");

        if (strTitle.trim().isEmpty() || strLink.trim().isEmpty() || strDisc.trim().isEmpty()) {
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder df = dbf.newDocumentBuilder();
                Document doc = df.newDocument();
                createRss(doc, response, request);
            } catch (Exception e) {
            }
        } else {
            Pattern pattern = Pattern.compile("(http://)[[a-z,0-9,A-Z].]*.");
            Matcher matcher = pattern.matcher(strLink);
            if (!matcher.matches()) {
                strLink = "http://" + strLink;
            }
            String value[] = {strTitle, strLink, strDisc};
            try {
                File file = new File("C:/Users/Nut/Documents/utain-lab4-parser/Utain-FeedWriter/web/db.sh");
                //if file doesnt exists, then create it
                if (!file.exists()) {
                    file.createNewFile();
                } else {
                    BufferedWriter bufferWritter = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));
                    bufferWritter.append(value[0] + "\n");
                    bufferWritter.append(value[1] + "\n");
                    bufferWritter.append(value[2] + "\n");
                    bufferWritter.append((new java.util.Date()).toString() + "\n");
                    bufferWritter.flush();
                    bufferWritter.close();
                }

                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder df = dbf.newDocumentBuilder();
                Document doc = df.newDocument();
                createRss(doc, response, request);

            } catch (Exception ex) {
                Logger.getLogger(FeedWriter.class.getName()).log(Level.SEVERE, null, ex);
            } finally {

            }
        }

    }
    static ArrayList<String> list;

    private void createRss(Document doc, HttpServletResponse res, HttpServletRequest req) throws Exception {
        req.setCharacterEncoding("UTF-8");
        res.setCharacterEncoding("UTF-8");
        res.setContentType("text/xml; charset=UTF-8");
        PrintWriter pw = res.getWriter();

        FileInputStream is;
        list = new ArrayList<String>();
        //reader
        is = new FileInputStream("C:/Users/Nut/Documents/utain-lab4-parser/Utain-FeedWriter/web/db.sh");
        //DataInputStream ds = new DataInputStream(is);
        //BufferedReader br = new BufferedReader(new InputStreamReader(ds, "UTF-8"));
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strLine;
        while ((strLine = br.readLine()) != null) {
            list.add(strLine);
        }
        br.close();
        //invert list
        Collections.reverse(list);
        try {
            //bluiding
            Element rssRoot = doc.createElement("rss");
            rssRoot.setAttribute("version", "2.0");
            doc.appendChild(rssRoot);
            {
                //create channel
                Element channel = doc.createElement("channel");
                rssRoot.appendChild(channel);
                {
                    //rss/channel/title
                    Element title = doc.createElement("title");
                    channel.appendChild(title);
                    Text titleT = doc.createTextNode("Nut Utain Wongpreaw\tอุเทน วงษ์เปรียว");
                    title.appendChild(titleT);
                    //rss/channel/description
                    Element desc = doc.createElement("description");
                    channel.appendChild(desc);
                    Text descT = doc.createTextNode("Utain Fedd Information News Rss Feed");
                    desc.appendChild(descT);
                    //rss/channel/link
                    Element link = doc.createElement("link");
                    channel.appendChild(link);
                    Text linkT = doc.createTextNode("http://www.utain.in.th");
                    link.appendChild(linkT);

                    Element lang = doc.createElement("language");
                    channel.appendChild(lang);
                    Text langT = doc.createTextNode("en");
                    lang.appendChild(langT);

                    for (int i = 0; i < list.size(); i += 4) {
                        Element item = doc.createElement("item");
                        channel.appendChild(item);

                        Element itemTitle = doc.createElement("title");
                        item.appendChild(itemTitle);
                        Text itemTitleText = doc.createTextNode(list.get(i + 3));
                        itemTitle.appendChild(itemTitleText);

                        Element itemLink = doc.createElement("link");
                        item.appendChild(itemLink);
                        Text itemLinkText = doc.createTextNode(list.get(i + 2));
                        itemLink.appendChild(itemLinkText);

                        Element itemDes = doc.createElement("description");
                        item.appendChild(itemDes);
                        Text itemDesText = doc.createTextNode(list.get(i + 1));
                        itemDes.appendChild(itemDesText);

                        Element itemPubDate = doc.createElement("pubDate");
                        item.appendChild(itemPubDate);
                        Text itemPubDateText = doc.createTextNode(list.get(i));
                        itemPubDate.appendChild(itemPubDateText);

                    }
                }
            }

            TransformerFactory tFact = TransformerFactory.newInstance();
            Transformer trans = tFact.newTransformer();
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            pw.print(writer.toString());

        } catch (TransformerException ex) {
            System.out.println("Error outputting document");
        } catch (Exception e) {
            System.out.println("Error building document");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    public String getSerString() {
        return "Short description";
    }
}
